package com.example.demo.service;

import com.example.demo.mapper.AppSettingMapper;
import com.example.demo.mapper.NoticeMapper;
import com.example.demo.mapper.TorrentMapper;
import com.example.demo.mapper.UserMapper;
import com.example.demo.model.AppSetting;
import com.example.demo.model.Notice;
import com.example.demo.model.Torrent;
import com.example.demo.model.User;
import com.example.demo.utils.JwtUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.List;
import java.util.Optional;

@Slf4j
@Service
public class AdminService {
    private final UserMapper userMapper;
    private final JwtUtils jwtUtils;

    private final ReportService reportService;

    private final NoticeMapper noticeMapper;
    private final AppSettingMapper appSettingMapper;

    private final TorrentMapper torrentMapper;

    private final TorrentSearchService torrentSearchService;


    @Autowired
    public AdminService(UserMapper userMapper, JwtUtils jwtUtils, ReportService reportService, NoticeMapper noticeMapper, AppSettingMapper appSettingMapper, TorrentMapper torrentMapper, TorrentSearchService torrentSearchService) {
        this.userMapper = userMapper;
        this.jwtUtils = jwtUtils;
        this.reportService = reportService;
        this.noticeMapper = noticeMapper;
        this.appSettingMapper = appSettingMapper;
        this.torrentMapper = torrentMapper;
        this.torrentSearchService = torrentSearchService;
    }

    public void processReport(Long reportId, Long adminId, String processResult, Integer actionTaken) {
        reportService.processReport(reportId, adminId, processResult, actionTaken);
    }

    @Transactional
    public String banUser(Long userId, String reason, Long banDurationDays, String adminUsername) {
        log.info("封禁用户操作开始 - 用户ID: {}, 原因: {}, 时长: {}天, 操作人: {}",
                userId, reason, banDurationDays, adminUsername);

        // 检查用户是否存在
        User user = userMapper.selectUserById(userId);
        if (user == null) {
            log.error("用户不存在 - ID: {}", userId);
            throw new IllegalArgumentException("用户不存在");
        }

        // 检查是否已封禁
        if (user.isBanned()) {
            log.warn("用户已被封禁 - ID: {}", userId);
            throw new IllegalStateException("用户已被封禁");
        }

        // 更新封禁状态
        user.setBanned(true);
        user.setBanReason(reason);
        user.setBanTime(LocalDateTime.now());
        user.setBanExpiry(LocalDateTime.now().plusDays(banDurationDays));

        int rows = userMapper.updateBanStatus(user);
        log.info("更新封禁状态 - 影响行数: {}", rows);

        // 使令牌失效
        try {
            jwtUtils.invalidateTokensForUser(userId);
            log.info("用户令牌已失效 - ID: {}", userId);
        } catch (Exception e) {
            log.error("令牌失效操作失败", e);
            throw new RuntimeException("令牌失效失败");
        }

        return String.format("用户 %s (ID: %d) 已被管理员 %s 封禁，时长 %d 小时。原因: %s",
                user.getUsername(), user.getId(), adminUsername, banDurationDays, reason);
    }

    @Transactional
    public String unbanUser(Long userId, String adminUsername) {
        User user = userMapper.selectUserById(userId);
        if (user == null) {
            throw new IllegalArgumentException("用户不存在");
        }
        if (!user.isBanned()) {
            throw new IllegalStateException("用户未被封禁");
        }

        // 清除所有封禁相关信息
        user.setBanned(false);
        user.setBanReason(null);
        user.setBanTime(null);
        user.setBanExpiry(null);

        log.info("解封用户: ID={}, 当前封禁状态={}", userId, user.isBanned());

        // 执行更新
        int rows = userMapper.updateBanStatus(user);
        log.info("数据库更新行数: {}", rows);
        if (rows == 0) {
            throw new RuntimeException("解封失败，数据库未更新");
        }

        return String.format("用户 %s (ID: %d) 已被管理员 %s 解封",
                user.getUsername(), user.getId(), adminUsername);
    }

    // 管理员发布新公告
    public Notice publishNotice(Long adminId, String topic, String content) {
        Notice notice = new Notice();
        notice.setCreatorId(adminId);
        notice.setNoticeTopic(topic);
        notice.setContent(content);
        notice.setCreateTime(LocalDateTime.now());
        noticeMapper.insertNotice(notice);
        return notice;
    }

    // 查询所有通知
    public List<Notice> getAllNotices() {
        return noticeMapper.findAll();
    }

    // 管理员删除公告
    public void deleteNotice(Long noticeId) {
        noticeMapper.deleteById(noticeId);
    }

    // 配置系统参数
    public AppSetting configureSystemParam(String configKey, Double configValue) {
        AppSetting config = new AppSetting();
        config.setConfigKey(configKey);
        config.setConfigValue(configValue);
        config.setLastUpdated(LocalDateTime.now());

        Optional<AppSetting> existingConfig = appSettingMapper.findByConfigKey(configKey);
        if (existingConfig.isPresent()) {
            config.setId(existingConfig.get().getId());
            appSettingMapper.updateConfig(config);
        } else {
            appSettingMapper.insertConfig(config);
        }
        return config;
    }

    public List<AppSetting> getAllSystemParam() {
        return appSettingMapper.findAll();
    }


    public List<Torrent> getPendingTorrents() {
        return torrentMapper.findByStatus(Torrent.Status.PENDING);
    }

    @Transactional
    public String reviewTorrent(Long torrentId, Integer status, Long adminId) {
        // 验证种子是否存在
        Torrent torrent = torrentMapper.findById(torrentId);
        if (torrent == null) {
            throw new IllegalArgumentException("种子不存在");
        }
        // 验证状态
        if (!List.of(Torrent.Status.APPROVED, Torrent.Status.REJECTED).contains(status)) {
            throw new IllegalArgumentException("无效的审核状态");
        }
        // 更新审核状态
        torrent.setStatus(status);
        torrent.setReviewedAt(LocalDateTime.now());
        torrent.setReviewedBy(adminId);
        int rows = torrentMapper.updateReviewStatus(torrentId, status, torrent.getReviewedAt(), adminId);
        if (rows == 0) {
            throw new RuntimeException("审核失败，数据库未更新");
        }
        // 同步更新 Elasticsearch 索引（如果使用）
        torrentSearchService.indexTorrent(torrent);
        return String.format("种子 %s (ID: %d) 已由管理员 %d %s",
                torrent.getFileName(), torrentId, adminId, status == Torrent.Status.APPROVED ? "通过" : "拒绝");
    }

    public List<User> getAllUsers() {
        return userMapper.findAllUsers();
    }

}